--[[ =========================================================================
   PLINKO ROCKET -- pour CC:Tweaked
   -------------------------------------------------------------------------
   A installer sur un ADVANCED COMPUTER avec :
     - un MONITEUR AVANCE tactile a cote (le plateau) : 7x5 blocs conseille
     - un Wired Modem
     - client_solde.lua et login_term.lua sur le meme computer

   Tu te connectes sur le terminal, tu choisis ton plateau et ta mise,
   puis tu laches les billes en touchant le moniteur.

   RTP : 99 % sur les trois plateaux. Les tables ont ete calibrees sur
   1,2 million de chutes simulees AVEC les obstacles, car Ronflex et
   l'Electrode deforment la distribution : une formule binomiale
   theorique aurait donne un resultat faux.
     - 8 rangees  : table a 99,0 %, pas de jackpot (la case extreme
                    tombe 1 fois sur 73, un progressif n'aurait pas le
                    temps de grossir)
     - 12 et 16   : table a 98,0 % + 1 % verse au jackpot progressif,
                    declenche environ 1 chute sur 1200
========================================================================= ]]

--------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  fps         = 15,
  betLevels   = { 10, 25, 50, 100, 250, 500, 10000 },
  autoBalls   = 10,
  jackpotFile = "plinko_jackpot.dat",
  jackpotSeed = 2000,        -- mise de depart de la cagnotte
  jackpotCut  = 0.01,        -- part de chaque mise versee au jackpot
  frameTime   = 4,           -- images d'animation par rangee
}

-- Tables de gains, mesurees et non theoriques (voir en-tete)
local BOARDS = {
  [8] = {
    rows = 8, jackpot = false,
    pays = { 9, 3, 1.2, 0.6, 0.42, 0.6, 1.2, 3, 9 },
    label = "PRUDENT",
  },
  [12] = {
    rows = 12, jackpot = true, jackpotSlots = 1,
    pays = { 30, 10, 3.5, 1.7, 1, 0.62, 0.36, 0.62, 1, 1.7, 3.5, 10, 30 },
    label = "EQUILIBRE",
  },
  [16] = {
    rows = 16, jackpot = true, jackpotSlots = 2,
    pays = { 100, 35, 13, 5, 2.5, 1.5, 0.9, 0.5, 0.31, 0.5, 0.9, 1.5,
             2.5, 5, 13, 35, 100 },
    label = "TEAM ROCKET",
  },
}
local BOARD_ORDER = { 8, 12, 16 }

--------------------------------------------------------------------------
-- PERIPHERIQUES
--------------------------------------------------------------------------
local bank  = dofile("client_solde.lua")
local login = dofile("login_term.lua")

local mon = peripheral.find("monitor")
if not mon then error("Aucun moniteur trouve (il doit etre avance).", 0) end

local speaker = peripheral.find("speaker")
local function beep(p, inst)
  if speaker then pcall(speaker.playNote, inst or "bit", 1, p or 12) end
end

--------------------------------------------------------------------------
-- PALETTE ET FRAMEBUFFER
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, ["1"] = 0xff7a18, ["2"] = 0xff2f8f, ["3"] = 0xc3c7d4,
  ["4"] = 0xffd23f, ["5"] = 0x9dff5c, ["6"] = 0xff5fb0, ["7"] = 0x14141c,
  ["8"] = 0x3c3c4a, ["9"] = 0x35e8ff, ["a"] = 0x8b5cd6, ["b"] = 0x1b3a8f,
  ["c"] = 0x5a1016, ["d"] = 0x2fa84f, ["e"] = 0xd11f2a, ["f"] = 0x000000,
}

mon.setTextScale(0.5)
for hex, rgb in pairs(PAL) do
  pcall(mon.setPaletteColour, 2 ^ tonumber(hex, 16), rgb)
end

local W, H = mon.getSize()
local ct, cf, cb = {}, {}, {}
local shakeX, shakeY = 0, 0

local function fbInit()
  W, H = mon.getSize()
  ct, cf, cb = {}, {}, {}
  for y = 1, H do ct[y], cf[y], cb[y] = {}, {}, {} end
end

local function clear(bg)
  bg = bg or "f"
  for y = 1, H do
    for x = 1, W do ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg end
  end
end

local function px(x, y, bg)
  x = math.floor(x + shakeX)
  y = math.floor(y + shakeY)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg
  end
end

local function rect(x1, y1, x2, y2, bg)
  for y = math.floor(y1), math.floor(y2) do
    for x = math.floor(x1), math.floor(x2) do px(x, y, bg) end
  end
end

local function text(x, y, s, fg, bg)
  x = math.floor(x + shakeX)
  y = math.floor(y + shakeY)
  for i = 1, #s do
    local xx = x + i - 1
    if xx >= 1 and xx <= W and y >= 1 and y <= H then
      ct[y][xx] = s:sub(i, i)
      cf[y][xx] = fg or "0"
      if bg then cb[y][xx] = bg end
    end
  end
end

local function center(x1, x2, y, s, fg, bg)
  text(math.floor(x1 + ((x2 - x1 + 1) - #s) / 2), y, s, fg, bg)
end

local function push()
  for y = 1, H do
    mon.setCursorPos(1, y)
    mon.blit(table.concat(ct[y]), table.concat(cf[y]), table.concat(cb[y]))
  end
end

fbInit()

--------------------------------------------------------------------------
-- FONTE 5x7
--------------------------------------------------------------------------
local FONT = {
  P="11110/10001/10001/11110/10000/10000/10000",
  L="10000/10000/10000/10000/10000/10000/11111",
  I="11111/00100/00100/00100/00100/00100/11111",
  N="10001/11001/10101/10011/10001/10001/10001",
  K="10001/10010/10100/11000/10100/10010/10001",
  O="01110/10001/10001/10001/10001/10001/01110",
  R="11110/10001/10001/11110/10100/10010/10001",
  C="01110/10001/10000/10000/10000/10001/01110",
  E="11111/10000/10000/11110/10000/10000/11111",
  T="11111/00100/00100/00100/00100/00100/00100",
  A="01110/10001/10001/11111/10001/10001/10001",
  J="00111/00010/00010/00010/00010/10010/01100",
  G="01110/10001/10000/10111/10001/10001/01111",
  M="10001/11011/10101/10101/10001/10001/10001",
  V="10001/10001/10001/10001/10001/01010/00100",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
}
local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows + 1] = r end
  GLYPH[ch] = rows
end

local function bigWidth(s, sx) sx = sx or 1; return #s * (5 * sx + sx) - sx end

local function bigText(x0, y0, s, colFn, sx, sy)
  sx, sy = sx or 1, sy or 1
  local cx = x0
  for i = 1, #s do
    local g = GLYPH[s:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      for rx = 1, 5 do
        if g[ry]:sub(rx, rx) == "1" then
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              px(cx + (rx - 1) * sx + ix, y0 + (ry - 1) * sy + iy,
                 colFn(cx + (rx - 1) * sx + ix, ry))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx
  end
end

--------------------------------------------------------------------------
-- SPRITES
--------------------------------------------------------------------------
local RONFLEX = {
  "...KKKKKKKKK...",
  "..KCCCCCCCCCK..",
  ".KCCEECCCEECCK.",
  ".KCCCCCCCCCCCK.",
  "KCCCCBBBBBCCCCK",
  "KCWWWWWWWWWWWCK",
  ".KWWWWWWWWWWWK.",
  "..KKKKKKKKKKK..",
}
local RONFLEX_MAP = { K = "f", C = "b", E = "f", B = "f", W = "3" }

local ELECTRODE = {
  "..KKKKK..",
  ".K00000K.",
  "K0K000K0K",
  "Keeeeeeek",
  ".KKeeeKK.",
}
local ELECTRODE_MAP = { K = "f", ["0"] = "0", e = "e", k = "f" }

local MIAOUSS = {
  "..KK...........KK..",
  ".KCCK.........KCCK.",
  "KCCCCCCCCCCCCCCCCCK",
  "KCCCCCCC444CCCCCCCK",
  "KCCEECCCCCCCCCEECCK",
  "KCCCCCCCBBBCCCCCCCK",
  ".KCCCCCCCCCCCCCCCK.",
  "..KKKKKKKKKKKKKKK..",
}
local MIAOUSS_MAP = { K = "f", C = "3", ["4"] = "4", E = "f", B = "e" }

local VOLTORBE = {
  "..eeeee..",
  ".eeeeeee.",
  "e0eeeee0e",
  ".0000000.",
  "..00000..",
}

local MOTTO = {
  "Pour proteger le monde de la devastation !",
  "Pour unir tous les peuples dans notre nation !",
  "Denoncer les mefaits de la verite et de l'amour !",
  "Etendre notre pouvoir jusqu'aux etoiles !",
  "La Team Rocket, plus vite que la lumiere !",
}

local BARKS = {
  "Encore une bille pour la caisse.",
  "Giovanni compte sur toi.",
  "Ronflex bloque encore une case...",
  "Vise les bords, si tu oses.",
  "La cagnotte n'attend que toi.",
  "Ce plateau est truque. Enfin, presque.",
}

local function drawSprite(art, x0, y0, map)
  for ry, row in ipairs(art) do
    for rx = 1, #row do
      local ch = row:sub(rx, rx)
      if ch ~= "." then
        px(x0 + rx - 1, y0 + ry - 1, map and (map[ch] or "0") or ch)
      end
    end
  end
end

--------------------------------------------------------------------------
-- JACKPOT PERSISTANT
--------------------------------------------------------------------------
local function loadJackpot()
  if not fs.exists(CFG.jackpotFile) then return CFG.jackpotSeed end
  local f = fs.open(CFG.jackpotFile, "r")
  local v = tonumber(f.readAll() or "")
  f.close()
  return v or CFG.jackpotSeed
end

local function saveJackpot(v)
  local f = fs.open(CFG.jackpotFile, "w")
  f.write(tostring(math.floor(v)))
  f.close()
end

local jackpot = loadJackpot()

--------------------------------------------------------------------------
-- MECANIQUE DE CHUTE
--------------------------------------------------------------------------
-- Le trajet complet est calcule AVANT l'animation : la bille ne fait
-- qu'illustrer un resultat deja tire, comme les rouleaux de la machine
-- a sous. C'est ce qui garantit que le RTP mesure est bien celui qui
-- s'applique en jeu.
local function computeDrop(R)
  local elecRow, elecCol, tunRow
  if math.random() < 0.60 then
    elecRow = math.random(2, R - 1)
    elecCol = math.random(0, elecRow - 1)
  end
  if math.random() < 0.25 then tunRow = math.random(3, R - 1) end

  local col = 0
  local path = { [0] = 0 }
  local marks = {}
  for row = 1, R do
    local d = math.random(0, 1)
    if elecRow == row and elecCol == col then
      d = (col < row / 2) and 0 or 1
      marks[row] = "elec"
    end
    col = col + d
    if tunRow == row then
      if col == 0 then col = row; marks[row] = "tunnel"
      elseif col == row then col = 0; marks[row] = "tunnel" end
    end
    path[row] = col
  end

  local slot = col
  local ron = math.random(1, R - 1)
  local bumped = false
  if slot == ron then
    slot = slot + ((math.random(0, 1) == 0) and -1 or 1)
    if slot < 0 then slot = 0 end
    if slot > R then slot = R end
    bumped = true
  end

  return { path = path, slot = slot, marks = marks, ron = ron,
           bumped = bumped, elecRow = elecRow, elecCol = elecCol,
           tunRow = tunRow }
end

--------------------------------------------------------------------------
-- MISE EN PAGE
--------------------------------------------------------------------------
local L = {}
local currentRows = 12

local function layout(R)
  fbInit()
  currentRows = R
  L.x1, L.y1, L.x2, L.y2 = 2, 2, W - 1, H - 1
  L.headH = 8
  L.slotY = L.y2 - 3
  L.boardTop = L.y1 + L.headH + 1
  L.stepY = math.max(1, math.floor((L.slotY - 2 - L.boardTop) / R))
  L.stepX = math.max(3, math.floor((L.x2 - L.x1 - 2) / (R + 1)))
  L.cx = math.floor((L.x1 + L.x2) / 2)
  L.boardH = R * L.stepY
end

local function pegPos(row, col)
  return L.cx + (col - row / 2) * L.stepX, L.boardTop + row * L.stepY
end

local function slotX(i, R)
  return L.cx + (i - R / 2) * L.stepX
end

--------------------------------------------------------------------------
-- ELEMENTS DU PLATEAU
--------------------------------------------------------------------------
local CHASE = { "4", "1", "e", "c" }
local function drawFrame(t, flash)
  local step = math.floor(t * 6)
  for x = 1, W do
    local a = flash and (((x + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((x + step) % 4) + 1]
    px(x, 1, a); px(x, H, a)
  end
  for y = 1, H do
    local a = flash and (((y + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((y + step) % 4) + 1]
    px(1, y, a); px(W, y, a)
  end
end

local function slotColor(i, R)
  local d = math.abs(i - R / 2) / (R / 2)
  if d > 0.92 then return "4" end
  if d > 0.70 then return "1" end
  if d > 0.45 then return "e" end
  if d > 0.22 then return "a" end
  return "b"
end

local function fmt(n)
  local s = tostring(math.floor(n))
  local out = ""
  while #s > 3 do out = " " .. s:sub(-3) .. out; s = s:sub(1, -4) end
  return s .. out
end

local function payText(v)
  if type(v) ~= "number" then return "?" end
  if v >= 10 then return "x" .. math.floor(v) end
  return "x" .. string.format("%.1f", v):gsub("%.0$", "")
end

local function drawBoard(t, board, hot, ron, elec, tun, giovanni)
  local R = board.rows
  -- fond du plateau
  rect(L.x1, L.boardTop - 1, L.x2, L.slotY - 1, giovanni and "c" or "7")

  -- clous
  for row = 1, R do
    for col = 0, row do
      local x, y = pegPos(row, col)
      local lit = hot and hot[row] == col
      local c = lit and "0" or (giovanni and "e" or "3")
      if elec and elec.row == row and elec.col == col then
        drawSprite(ELECTRODE, x - 4, y - 2, ELECTRODE_MAP)
      elseif tun == row and (col == 0 or col == row) then
        rect(x - 1, y - 1, x + 1, y + 1, "d")
        text(x, y, "O", "f", "d")
      else
        px(x, y, c)
        if lit then
          px(x - 1, y, "4"); px(x + 1, y, "4")
        end
      end
    end
  end

  -- cases d'arrivee
  for i = 0, R do
    local x = slotX(i, R)
    local col = slotColor(i, R)
    local isJack = board.jackpot and
                   (i < board.jackpotSlots or i > R - board.jackpotSlots)
    if isJack then col = (math.floor(t * 6) % 2 == 0) and "0" or "4" end
    local w = math.max(1, math.floor(L.stepX / 2))
    rect(x - w, L.slotY, x + w, L.slotY + 1, col)
    local label = isJack and "JACK" or payText(board.pays[i + 1])
    center(x - w, x + w, L.slotY, label:sub(1, 2 * w + 1), "f", col)
    if ron == i then
      drawSprite(RONFLEX, x - 7, L.slotY - 8, RONFLEX_MAP)
    end
  end
end

local function drawHead(t, board, credit, bet, msg, msgCol)
  rect(L.x1, L.y1, L.x2, L.y1 + L.headH - 1, "f")

  -- titre
  local w = bigWidth("PLINKO")
  bigText(L.x1 + 2, L.y1 + 1, "PLINKO", function(_, gy)
    return gy <= 3 and "4" or "e"
  end)

  -- cagnotte progressive, dans son propre cadre
  local js = fmt(jackpot)
  local jw = bigWidth(js)
  local jx = L.x1 + w + 8
  if jx + jw + 4 < L.x2 - 18 then
    rect(jx - 2, L.y1, jx + jw + 1, L.y1 + L.headH - 1, "c")
    center(jx - 2, jx + jw + 1, L.y1, "JACKPOT ROCKET", "6", "c")
    bigText(jx, L.y1 + 1, js, function(_, gy)
      if math.floor(t * 3) % 2 == 0 and gy <= 2 then return "0" end
      return gy <= 3 and "4" or "1"
    end)
  else
    text(L.x1 + 2, L.y1 + L.headH - 1, "JACKPOT " .. js, "4")
  end

  -- infos de droite
  local info = board.label .. "  " .. board.rows .. " RANGEES"
  text(L.x2 - #info + 1, L.y1, info, "3")
  if credit then
    local c = "CREDIT " .. fmt(credit)
    text(L.x2 - #c + 1, L.y1 + 2, c, "4")
  end
  if bet then
    local b = "MISE " .. fmt(bet)
    text(L.x2 - #b + 1, L.y1 + 3, b, "5")
  end
  if msg then
    text(L.x2 - #msg + 1, L.y1 + 5, msg, msgCol or "0")
  end
end

local function drawHistory(hist, board)
  local y = L.slotY + 2
  if y > L.y2 then y = L.y2 end
  local s = "DERNIERES : "
  text(L.x1, y, s, "8")
  local x = L.x1 + #s
  for i = math.max(1, #hist - 12), #hist do
    local e = hist[i]
    -- chaque entree garde son propre plateau : une case du 16 rangees
    -- n'existe pas sur le 8 rangees
    if type(e) == "table" and e.pay then
      local lbl = payText(e.pay)
      if x + #lbl + 1 > L.x2 then break end
      text(x, y, lbl, slotColor(e.slot, e.rows))
      x = x + #lbl + 1
    end
  end
end

--------------------------------------------------------------------------
-- CLINS D'OEIL
--------------------------------------------------------------------------
local egg, eggIdx = nil, 0
local giovanni = 0            -- horodatage de fin du mode Giovanni
local clickCount, clickTime = 0, 0

local function triggerEgg()
  local kinds = { "miaouss", "voltorbe", "motto" }
  eggIdx = (eggIdx % #kinds) + 1
  egg = { kind = kinds[eggIdx], start = os.clock() }
  beep(18, "harp")
end

local function drawEgg(t, balls)
  if not egg then return end
  local age = t - egg.start
  if age > 6 then egg = nil; return end

  if egg.kind == "miaouss" then
    local u = age / 5
    if u > 1 then egg = nil; return end
    local x = L.x1 + (L.x2 - L.x1 - 19) * u
    local y = L.slotY - 10 + math.floor(math.sin(age * 9) + 0.5)
    drawSprite(MIAOUSS, x, y, MIAOUSS_MAP)
    center(L.x1, L.x2, y - 2, "Miaouss souffle sur la bille !", "4")
    -- il pousse les billes en cours d'un cran
    for _, b in ipairs(balls or {}) do b.nudge = 1 end

  elseif egg.kind == "voltorbe" then
    if age < 2 then
      local x = L.x1 + (L.cx - L.x1) * (age / 2)
      drawSprite(VOLTORBE, x, L.slotY - 8, nil)
      center(L.x1, L.x2, L.slotY - 10, "Un Voltorbe sur le plateau !", "5")
    else
      local r = (age - 2) * 20
      for yy = L.boardTop, L.slotY do
        for xx = L.x1, L.x2 do
          local dx = (xx - L.cx) / 1.9
          local dy = yy - (L.slotY - 6)
          local d = math.sqrt(dx * dx + dy * dy)
          if math.abs(d - r) < 1.3 then px(xx, yy, "0")
          elseif math.abs(d - r) < 2.4 then px(xx, yy, "4")
          elseif math.abs(d - r) < 3.4 then px(xx, yy, "1") end
        end
      end
      if age > 4.5 then egg = nil end
    end

  elseif egg.kind == "motto" then
    local idx = math.min(#MOTTO, math.floor(age / 1.1) + 1)
    center(L.x1, L.x2, L.boardTop + 1, MOTTO[idx], "6")
    for i = 1, 40 do
      local sx = L.x1 + ((i * 37 + math.floor(age * 11)) % (L.x2 - L.x1))
      local sy = L.boardTop + ((i * 13 + math.floor(age * 17)) % 8)
      px(sx, sy, ({ "4", "e", "0", "6" })[(i % 4) + 1])
    end
  end
end

--------------------------------------------------------------------------
-- ETAT PARTAGE
--------------------------------------------------------------------------
local STATE = { playing = false }
local history = {}

local function pushHistory(entry)
  history[#history + 1] = entry
  while #history > 40 do table.remove(history, 1) end
end

--------------------------------------------------------------------------
-- ANIMATION D'UNE SERIE DE BILLES
--------------------------------------------------------------------------
-- balls : chacune a son trajet precalcule ; elles tombent en cascade
local function runBalls(board, bet, player, count, credit)
  local R = board.rows
  local balls, effects = {}, {}
  local pending = count
  local totalGain, jackWon = 0, 0
  local nextDrop = 0
  local t0 = os.clock()
  local finished = 0
  local msg, msgCol = nil, "0"

  local timer = os.startTimer(1 / CFG.fps)
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local now = os.clock()

    if ev == "monitor_touch" then
      -- toucher l'ecran accelere la cascade
      nextDrop = 0

    elseif ev == "timer" and p1 == timer then
      timer = os.startTimer(1 / CFG.fps)
      local t = now - t0

      -- lacher les billes en cascade
      if pending > 0 and now >= nextDrop then
        pending = pending - 1
        nextDrop = now + 0.45
        local d = computeDrop(R)
        d.frame = 0
        d.total = R * CFG.frameTime
        balls[#balls + 1] = d
        beep(16)
      end

      -- avancer les billes
      local hot = {}
      for i = #balls, 1, -1 do
        local b = balls[i]
        b.frame = b.frame + 1
        local row = math.floor(b.frame / CFG.frameTime)
        local f = (b.frame % CFG.frameTime) / CFG.frameTime
        if row >= R then
          -- arrivee
          local slot = b.slot
          local isJack = board.jackpot and
                         (slot < board.jackpotSlots or slot > R - board.jackpotSlots)
          local gain
          if isJack then
            gain = math.floor(jackpot)
            jackWon = jackWon + gain
            jackpot = CFG.jackpotSeed
            saveJackpot(jackpot)
            shakeX, shakeY = 1, 1
            effects[#effects + 1] = { kind = "jackpot", born = now,
                                      x = slotX(slot, R) }
            beep(24, "bell")
          else
            gain = math.floor(bet * board.pays[slot + 1])
            effects[#effects + 1] = { kind = "win", born = now,
                                      x = slotX(slot, R), gain = gain,
                                      slot = slot }
            beep(10 + math.floor(board.pays[slot + 1]), "bell")
          end
          totalGain = totalGain + gain
          pushHistory({ slot = slot, rows = R, pay = board.pays[slot + 1] })
          table.remove(balls, i)
          finished = finished + 1
        else
          hot[row] = b.path[row]
        end
      end

      -- rendu
      if shakeX ~= 0 then
        shakeX = (math.random(0, 1) == 0) and 1 or -1
        shakeY = (math.random(0, 1) == 0) and 1 or 0
      end
      clear("f")
      local giov = (now < giovanni)
      local ron = balls[1] and balls[1].ron or nil
      local elec = balls[1] and balls[1].elecRow and
                   { row = balls[1].elecRow, col = balls[1].elecCol } or nil
      drawBoard(t, board, hot, ron, elec, balls[1] and balls[1].tunRow, giov)

      -- les billes, avec leur trainee
      for _, b in ipairs(balls) do
        local row = math.floor(b.frame / CFG.frameTime)
        local f = (b.frame % CFG.frameTime) / CFG.frameTime
        local c0 = b.path[row] or 0
        local c1 = b.path[math.min(R, row + 1)] or c0
        local x0, y0 = pegPos(row, c0)
        local x1, y1 = pegPos(row + 1, c1)
        local x = x0 + (x1 - x0) * f
        local y = y0 + (y1 - y0) * f - math.sin(f * math.pi) * 1.2
        -- trainee
        px(x, y - 1, "c")
        px(x, y + 1, "e")
        -- la bille : une Poke Ball
        px(x - 1, y, "e"); px(x, y, "0"); px(x + 1, y, "e")
        if b.marks[row] == "elec" then
          center(x - 6, x + 6, y - 2, "ZAP !", "9")
        elseif b.marks[row] == "tunnel" then
          center(x - 8, x + 8, y - 2, "TUYAU !", "d")
        end
      end

      -- effets
      for i = #effects, 1, -1 do
        local e = effects[i]
        local age = now - e.born
        if age > 2.2 then
          table.remove(effects, i)
          if e.kind == "jackpot" then shakeX, shakeY = 0, 0 end
        elseif e.kind == "win" then
          local w = math.max(1, math.floor(L.stepX / 2))
          if math.floor(age * 8) % 2 == 0 then
            rect(e.x - w, L.slotY, e.x + w, L.slotY + 1, "0")
          end
          center(e.x - 8, e.x + 8, L.slotY - 2 - math.floor(age * 3),
                 "+" .. fmt(e.gain), e.gain >= bet and "5" or "8")
        else
          local txt = "JACKPOT !"
          local bw = bigWidth(txt)
          bigText(math.floor(L.cx - bw / 2), L.boardTop + 4, txt,
                  function(_, gy)
                    if math.floor(age * 8) % 2 == 0 then return "0" end
                    return gy <= 3 and "4" or "e"
                  end)
          for k = 1, 60 do
            local sx = L.x1 + ((k * 29 + math.floor(age * 21)) % (L.x2 - L.x1))
            local sy = L.boardTop + ((k * 7 + math.floor(age * 13))
                       % (L.slotY - L.boardTop))
            px(sx, sy, ({ "4", "0", "e", "6" })[(k % 4) + 1])
          end
        end
      end

      drawHead(t, board, credit, bet, msg, msgCol)
      drawHistory(history, board)
      drawEgg(now, balls)
      drawFrame(t, jackWon > 0)
      push()

      if pending == 0 and #balls == 0 and #effects == 0 then
        break
      end
    end
  end

  shakeX, shakeY = 0, 0
  return totalGain, jackWon
end

--------------------------------------------------------------------------
-- ECRAN DE VEILLE
--------------------------------------------------------------------------
local demoBalls = {}
local function attractFrame(t)
  local board = BOARDS[currentRows]
  local R = board.rows

  -- des billes tombent toutes seules, en demonstration
  if #demoBalls < 3 and math.random() < 0.06 then
    local d = computeDrop(R)
    d.frame = 0
    demoBalls[#demoBalls + 1] = d
  end
  local hot = {}
  for i = #demoBalls, 1, -1 do
    local b = demoBalls[i]
    b.frame = b.frame + 1
    local row = math.floor(b.frame / CFG.frameTime)
    if row >= R then
      pushHistory({ slot = b.slot, rows = R, pay = board.pays[b.slot + 1] })
      table.remove(demoBalls, i)
    else
      hot[row] = b.path[row]
    end
  end

  clear("f")
  local giov = (os.clock() < giovanni)
  drawBoard(t, board, hot, demoBalls[1] and demoBalls[1].ron, nil, nil, giov)

  for _, b in ipairs(demoBalls) do
    local row = math.floor(b.frame / CFG.frameTime)
    local f = (b.frame % CFG.frameTime) / CFG.frameTime
    local c0 = b.path[row] or 0
    local c1 = b.path[math.min(R, row + 1)] or c0
    local x0, y0 = pegPos(row, c0)
    local x1, y1 = pegPos(row + 1, c1)
    local x = x0 + (x1 - x0) * f
    local y = y0 + (y1 - y0) * f - math.sin(f * math.pi) * 1.2
    px(x - 1, y, "e"); px(x, y, "0"); px(x + 1, y, "e")
  end

  drawHead(t, board, nil, nil, nil, nil)
  -- une seule ligne de message : consigne et repliques du sbire alternent
  if math.floor(t / 4) % 2 == 0 then
    center(L.x1, L.x2, L.boardTop - 1,
           "DEMONSTRATION - inscris-toi sur le terminal", "3")
  else
    center(L.x1, L.x2, L.boardTop - 1,
           BARKS[(math.floor(t / 8) % #BARKS) + 1], "6")
  end

  -- un sbire commente les chutes


  drawHistory(history, board)
  drawEgg(os.clock(), demoBalls)
  drawFrame(t, giov)
  push()
end

local function attractLoop()
  while true do
    if not STATE.playing then
      local ok = pcall(attractFrame, os.clock())
      if not ok then sleep(0.5) end
    end
    sleep(1 / 8)
  end
end

-- les clics sur le moniteur pendant la veille declenchent les clins d'oeil
local function touchLoop()
  while true do
    os.pullEvent("monitor_touch")
    if not STATE.playing then
      local now = os.clock()
      if now - clickTime < 2 then clickCount = clickCount + 1
      else clickCount = 1 end
      clickTime = now
      if clickCount >= 10 then
        clickCount = 0
        giovanni = now + 20
        beep(4, "bass")
      else
        triggerEgg()
      end
    end
  end
end

--------------------------------------------------------------------------
-- TERMINAL
--------------------------------------------------------------------------
local TW, TH = term.getSize()

local function tFill(y, bg)
  term.setBackgroundColor(bg)
  term.setCursorPos(1, y)
  term.write(string.rep(" ", TW))
end

local function tLabel(x, y, s, fg, bg)
  term.setCursorPos(x, y)
  term.setTextColor(fg)
  term.setBackgroundColor(bg or colors.black)
  term.write(s)
end

local function tCenter(y, s, fg, bg)
  tLabel(math.floor((TW - #s) / 2) + 1, y, s, fg, bg)
end

local function splash()
  term.setBackgroundColor(colors.black)
  term.clear()
  tFill(1, colors.red)
  tCenter(1, "PLINKO ROCKET", colors.yellow, colors.red)
  tCenter(3, "Jackpot : " .. fmt(jackpot) .. " credits", colors.yellow)
  tCenter(5, "Trois plateaux, RTP 99 %", colors.white)
  tCenter(6, "Prudent 8 - Equilibre 12 - Team Rocket 16", colors.lightGray)
  tCenter(8, "Attention a Ronflex et a l'Electrode", colors.orange)
  tCenter(TH - 2, "Une touche pour jouer", colors.yellow)
  while true do
    local ev = os.pullEvent()
    if ev == "key" or ev == "mouse_click" then return end
  end
end

local function lobby(player)
  local betIdx, boardIdx = 3, 2
  local credit = bank.getBalance(player)
  local buttons

  local function draw(msg, col)
    buttons = {}
    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tLabel(2, 1, "PLINKO ROCKET", colors.yellow, colors.red)
    local right = player .. "  " .. fmt(credit)
    tLabel(TW - #right, 1, right, colors.white, colors.red)

    tCenter(3, "JACKPOT " .. fmt(jackpot), colors.yellow)

    tLabel(2, 5, "PLATEAU", colors.lightGray)
    for i, r in ipairs(BOARD_ORDER) do
      local x = 2 + (i - 1) * 16
      local sel = (i == boardIdx)
      term.setBackgroundColor(sel and colors.green or colors.gray)
      term.setCursorPos(x, 6)
      term.write(string.rep(" ", 15))
      tLabel(x + 1, 6, BOARDS[r].label:sub(1, 13),
             sel and colors.white or colors.lightGray,
             sel and colors.green or colors.gray)
      tLabel(x + 1, 7, r .. " rangees", colors.lightGray)
      buttons[#buttons + 1] = { id = "board" .. i, x1 = x, x2 = x + 14, y = 6 }
    end

    tLabel(2, 9, "MISE", colors.lightGray)
    term.setBackgroundColor(colors.red)
    term.setCursorPos(8, 9); term.write(" - ")
    buttons[#buttons + 1] = { id = "bet-", x1 = 8, x2 = 10, y = 9 }
    term.setBackgroundColor(colors.green)
    term.setCursorPos(20, 9); term.write(" + ")
    buttons[#buttons + 1] = { id = "bet+", x1 = 20, x2 = 22, y = 9 }
    tLabel(13, 9, fmt(CFG.betLevels[betIdx]), colors.yellow)

    term.setBackgroundColor(colors.green)
    term.setCursorPos(2, 11); term.write(string.rep(" ", 20))
    tLabel(5, 11, "LACHER 1 BILLE", colors.white, colors.green)
    buttons[#buttons + 1] = { id = "one", x1 = 2, x2 = 21, y = 11 }

    term.setBackgroundColor(colors.blue)
    term.setCursorPos(24, 11); term.write(string.rep(" ", 20))
    tLabel(27, 11, "AUTO x" .. CFG.autoBalls, colors.white, colors.blue)
    buttons[#buttons + 1] = { id = "auto", x1 = 24, x2 = 43, y = 11 }

    term.setBackgroundColor(colors.red)
    term.setCursorPos(TW - 11, 11); term.write(string.rep(" ", 10))
    tLabel(TW - 9, 11, "QUITTER", colors.white, colors.red)
    buttons[#buttons + 1] = { id = "quit", x1 = TW - 11, x2 = TW - 2, y = 11 }

    local b = BOARDS[BOARD_ORDER[boardIdx]]
    tCenter(13, b.jackpot and "Ce plateau alimente et peut gagner le jackpot"
            or "Ce plateau ne joue pas le jackpot", colors.lightGray)

    tFill(TH, colors.gray)
    if msg then tCenter(TH, msg, col or colors.white, colors.gray) end
  end

  draw("Espace = 1 bille, A = auto, +/- = mise")
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local action
    if ev == "mouse_click" then
      for _, b in ipairs(buttons) do
        if p3 == b.y and p2 >= b.x1 and p2 <= b.x2 then action = b.id end
      end
    elseif ev == "key" then
      if p1 == keys.q then action = "quit"
      elseif p1 == keys.space or p1 == keys.enter then action = "one"
      elseif p1 == keys.a then action = "auto"
      elseif p1 == keys.equals or p1 == keys.numPadAdd then action = "bet+"
      elseif p1 == keys.minus or p1 == keys.numPadSubtract then action = "bet-"
      elseif p1 == keys.one then action = "board1"
      elseif p1 == keys.two then action = "board2"
      elseif p1 == keys.three then action = "board3"
      end
    end

    if action == "quit" then return
    elseif action == "bet+" then
      betIdx = math.min(betIdx + 1, #CFG.betLevels); draw()
    elseif action == "bet-" then
      betIdx = math.max(betIdx - 1, 1); draw()
    elseif action and action:sub(1, 5) == "board" then
      boardIdx = tonumber(action:sub(6)); layout(BOARD_ORDER[boardIdx]); draw()
    elseif action == "one" or action == "auto" then
      local count = (action == "auto") and CFG.autoBalls or 1
      local bet = CFG.betLevels[betIdx]
      local total = bet * count
      local newBal, err = bank.addBalance(player, -total)
      if not newBal then
        draw(err or "Banque injoignable", colors.red)
      else
        credit = newBal
        local board = BOARDS[BOARD_ORDER[boardIdx]]
        if board.jackpot then
          jackpot = jackpot + total * CFG.jackpotCut
          saveJackpot(jackpot)
        end
        layout(board.rows)
        STATE.playing = true
        term.setBackgroundColor(colors.black)
        term.clear()
        tCenter(math.floor(TH / 2) - 1, "REGARDE LE MONITEUR", colors.yellow)
        tCenter(math.floor(TH / 2) + 1,
                count .. " bille(s) de " .. fmt(bet), colors.white)
        local gain, jack = runBalls(board, bet, player, count, credit)
        STATE.playing = false
        if gain > 0 then
          local nb = bank.addBalance(player, gain)
          credit = nb or (credit + gain)
        end
        local msg = "Gain : " .. fmt(gain) .. " sur " .. fmt(total) .. " mise"
        if jack > 0 then msg = "JACKPOT ! " .. fmt(jack) .. " credits" end
        draw(msg, (gain >= total) and colors.lime or colors.orange)
      end
    end
  end
end

--------------------------------------------------------------------------
-- PROGRAMME PRINCIPAL
--------------------------------------------------------------------------
math.randomseed((os.epoch and os.epoch("utc") or os.time()) % 2147483647)
layout(12)

local function mainLoop()
  while true do
    splash()
    local player = login.authenticate("Connexion Plinko Rocket")
    if player then lobby(player) end
  end
end

local ok, err = pcall(function()
  parallel.waitForAny(mainLoop, attractLoop, touchLoop)
end)

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
mon.setBackgroundColour(colours.black)
mon.clear()
if not ok and err ~= "Terminated" then error(err, 0) end
print("Plinko Rocket : arret.")
